package com.hjxy.codetools.controller;


import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "api")
public class FileController {
    @PostMapping(value = "fileUpload")
    public Map<String,Object> fileUpload(@RequestParam("file") MultipartFile multipartFile) throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        OutputStream out=null;
        try {
            //获取文件字节数组
            String fileName = multipartFile.getOriginalFilename();

            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            String newFileName=System.currentTimeMillis()+"."+suffix;

            byte [] bytes = multipartFile.getBytes();
            //文件存储路径(/fileupload1/ 这样会在根目录下创建问价夹)
            File pfile = new File("/xxx/upload/");

            //判断文件夹是否存在
            if(!pfile.exists()){
                //不存在时,创建文件夹
                pfile.mkdirs();
            }
            //创建文件
            File file = new File(pfile, newFileName);
            //写入指定文件夹
            out= new FileOutputStream(file);
            out.write(bytes);
            //resultMap.put("data",pfile+"\\"+fileName);
            //目前看来 前台控件只能显示 网络上的图片路径地址
           resultMap.put("data","xxx/upload/"+fileName);
            resultMap.put("code",20000);
        } catch (IOException e) {
            e.printStackTrace();
            //  return dealResultMap(false, "上传失败");
            resultMap.put("code",40000);
        }
        finally {
            out.close();

        }

        return  resultMap;

    }
}
